package com.example.jimuyutabletcontrol.network.tcp;

import android.text.TextUtils;
import android.util.Log;

import com.example.jimuyutabletcontrol.activity.SelectAUVRecordDataActivity;
import com.example.jimuyutabletcontrol.utils.Constants;
import com.example.jimuyutabletcontrol.utils.MsgType;
import com.google.gson.Gson;

import java.io.BufferedWriter;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;
import java.util.Timer;
import java.util.TimerTask;

/**
 * @author: HDX
 * @date: 2020\4\28 0028
 */
public class FileDown {

    private TCPSocket.NetTask task;

    private Runnable runnable;

    private Socket receiveSocket;

    private boolean threadRunning = false;

    private static FileDown fileDown;

    private Timer timer;

    private TimerTask timerTask;

    public synchronized static FileDown getInstance() {
        if (null == fileDown) {
            fileDown = new FileDown();
        }
        return fileDown;
    }

    private FileDown() {
    }

    public void startDown(TCPSocket.NetTask task, Runnable runnable) {
        if (threadRunning) return;
        this.task = task;
        this.runnable = runnable;
        threadRunning = true;
        setTimeOut();
        receiveMessage();
        sendMessage(task.fileName);
    }

    private void setTimeOut() {
        if (null != timer) {
            timer.purge();
            timer.cancel();
        }
        if (null != timerTask) {
            timerTask.cancel();
        }
        timer = new Timer();
        timerTask = new TimerTask() {
            @Override
            public void run() {
                if (threadRunning) {
                    if (null != runnable) {
                        runnable.run();
                    }
                    if (null != task) {
                        if (null != task.faileRunnable) {
                            task.faileRunnable.run();
                        }
                    }
                    threadRunning = false;
                }
            }
        };
    }

    private void sendMessage(final String message) {
        new Thread(() -> {
            Socket socket = null;
            try {
                socket = new Socket(Constants.TCP_SERVER_IP, Constants.TCP_SERVER_PORT);
            } catch (IOException e) {
                e.printStackTrace();
            }
            DataOutputStream pw = null;
            try {
                pw = new DataOutputStream(socket.getOutputStream());
                System.out.println("tcp order: " + "get," + message);
                pw.writeUTF("get," + message);
                pw.close();
                socket.close();
                if (null != timer && null != timerTask) {
                    timer.schedule(timerTask, 10000);
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }).start();
    }

    private void receiveMessage() {
        new Thread(() -> {
            File pathDS;
            File pathDH;
            DataInputStream dataInputStream = null;
            try {
                receiveSocket = new Socket(Constants.TCP_SERVER_IP, Constants.TCP_SERVER_PORT);
                OutputStream outputStream = receiveSocket.getOutputStream();
                DataOutputStream dataOutputStream = new DataOutputStream(outputStream);
                dataOutputStream.writeUTF("dataclient");
                InputStream inputStream = receiveSocket.getInputStream();
                dataInputStream = new DataInputStream(inputStream);
                pathDH = new File(Constants.FILE_PATH + Constants.DH);
                pathDS = new File(Constants.FILE_PATH + Constants.DS);
                if (!pathDH.exists()) {
                    pathDH.mkdirs();
                }
                if (!pathDS.exists()) {
                    pathDS.mkdirs();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
            if (null == dataInputStream) return;
            while (threadRunning) {
                try {
                    File file = null;
                    BufferedWriter bw = null;
                    String content = dataInputStream.readUTF();
                    System.out.println("content: " + content);
                    while (content != null) {
                        if (content.contains(".txt")) {
                            if (content.contains("DH")) {
                                file = new File(Constants.FILE_PATH + Constants.DH + task.fileName);
                            } else {
                                file = new File(Constants.FILE_PATH + Constants.DS + task.fileName);
                            }
                            if (!file.exists()) {
                                file.createNewFile();
                            }
                            bw = new BufferedWriter(new FileWriter(file));
                        } else if (content.contains("END")) {
                            bw.close();
                            receiveSocket.close();
                            threadRunning = false;
                            content = null;
                            if (null != task && null != task.runnable) {
                                task.runnable.run();
                            }
                            if (null != runnable) {
                                runnable.run();
                            }
                            if (null != timer) {
                                timer.purge();
                                timer.cancel();
                                timer = null;
                            }
                            if (null != timerTask) {
                                timerTask.cancel();
                                timerTask = null;
                            }
                            break;
                        } else {
                            bw.write(content + "\n");
                            bw.flush();
                        }
                        content = dataInputStream.readUTF();
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }).start();
    }
}
